package org.hanbo.code.repository.action;

import org.hanbo.code.repository.persistence.entity.RegisteredUser;
import org.hanbo.code.repository.persistence.entity.RegisteredUserDAO;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.opensymphony.xwork2.ActionSupport;

public class GaeActionSupportBase extends ActionSupport
{
	private static final long serialVersionUID = -5975453138882060253L;
	
	protected static String REGISTRATION = "registration";
	private User loggedInUser;
	private String stageValue;
	
	protected boolean checkLogin()
	{
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user == null)
		{
			stageValue = LOGIN;
			return false;
		}
		loggedInUser = user;
		
		return true;
	}

	protected boolean checkRegistration()
	{
		String userEmail = loggedInUser.getEmail();
		RegisteredUserDAO regUserDAO = new RegisteredUserDAO();
		regUserDAO.acquirePersistenceManager();
		boolean isUserRegistered = regUserDAO.isUserRegistered(userEmail);
		regUserDAO.releasePersistenceManager();
		
		if (!isUserRegistered)
		{
			stageValue = REGISTRATION; 
			return false; 
		}
		
		return true;
	}

	protected boolean checkUserStatus()
	{
		String userEmail = loggedInUser.getEmail();
		RegisteredUserDAO regUserDAO = new RegisteredUserDAO();
		regUserDAO.acquirePersistenceManager();
		RegisteredUser regUser = regUserDAO.getRegisteredUserByEmail(userEmail);
		regUserDAO.releasePersistenceManager();
		
		return regUser.getUserActiveStatus();
	}
	
	protected User getLoggedInUser()
	{
		return this.loggedInUser;
	}
	
	protected RegisteredUser getRegisteredUser()
	{
		String userEmail = loggedInUser.getEmail();
		RegisteredUserDAO regUserDAO = new RegisteredUserDAO();
		regUserDAO.acquirePersistenceManager();
		RegisteredUser regUser = regUserDAO.getRegisteredUserByEmail(userEmail);
		regUserDAO.releasePersistenceManager();
		
		return regUser;
	}
	
	protected String getCurrentStageValue()
	{
		return this.stageValue;
	}
	
	protected static String createLogInLink(String redirectUrl)
	{
		UserService userService = UserServiceFactory.getUserService();
		return userService.createLoginURL(redirectUrl);
	}

	protected static String createLogOutLink(String redirectUrl)
	{
		UserService userService = UserServiceFactory.getUserService();
		return userService.createLogoutURL(redirectUrl);
	}
}
